package com.oraycn.esbasic.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.netty.buffer.ByteBuf; 

public class SerializeUtils {
    public SerializeUtils() {
    }

    public static void writeDataWithIntLen(ByteBuf buffer, byte[] data) {
        buffer.writeInt(data.length);
        buffer.writeBytes(data);
    }

    public static void writeDataWithByteLen(ByteBuf buffer, byte[] data) {
        buffer.writeByte(data.length);
        buffer.writeBytes(data);
    }

    public static void writeDataWithByteLenFillZeo(ByteBuf buffer, byte[] data, int len) {
        buffer.writeByte(data.length);
        buffer.writeBytes(data);

        for(int writed = data.length; writed < len; ++writed) {
            buffer.writeByte(0);
        }

    }

    public static String readStrIntLen(ByteBuf buffer) throws IOException {
        int len = buffer.readInt();
        if (len <= 0) {
            return "";
        } else {
            byte[] arrayOfByte = new byte[len];
            buffer.readBytes(arrayOfByte);
            return new String(arrayOfByte, "utf-8");
        }
    }

    public static String readStrByteLenFixLen(ByteBuf buffer, byte len) throws IOException {
        byte realLen = buffer.readByte();
        if (realLen <= 0) {
            return "";
        } else {
            byte[] data = new byte[len];
            buffer.readBytes(data);
            return new String(data, 0, realLen, "utf-8");
        }
    }

    public static List<String> readStrList(ByteBuf paramByteBuf) throws IOException {
        ArrayList localArrayList = new ArrayList();
        int i;
        if ((i = paramByteBuf.readInt()) <= 0) {
            return localArrayList;
        } else {
            for(int j = 0; j < i; ++j) {
                byte[] arrayOfByte = new byte[paramByteBuf.readInt()];
                paramByteBuf.readBytes(arrayOfByte);
                localArrayList.add(new String(arrayOfByte, "utf-8"));
            }

            return localArrayList;
        }
    }

    public static List<byte[]> readByteList(ByteBuf paramByteBuf) throws IOException {
        List localArrayList = new ArrayList();
        int i;
        if ((i = paramByteBuf.readInt()) <= 0) {
            return localArrayList;
        } else {
            for(int j = 0; j < i; ++j) {
                int length = paramByteBuf.readInt();
                byte[] arrayOfByte = new byte[length];
                paramByteBuf.readBytes(arrayOfByte);
                localArrayList.add(arrayOfByte);
            }

            return localArrayList;
        }
    }
}
